package com.chanjiedata.changbs.module.main;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chanjiedata.changbs.R;
import com.chanjiedata.changbs.adapter.ActMachineAdapter;
import com.chanjiedata.changbs.adapter.NoActMachineAdapter;
import com.chanjiedata.changbs.base.BaseFragment;
import com.chanjiedata.changbs.net.Apis;
import com.chanjiedata.changbs.net.NetworkManager;
import com.chanjiedata.changbs.net.interfaces.OnRequestCallBack;
import com.chanjiedata.changbs.proto.Mystock;
import com.chanjiedata.changbs.utlis.ValidateUtils;
import com.chanjiedata.changbs.view.easyadapter.RecyclerArrayAdapter;
import com.google.protobuf.InvalidProtocolBufferException;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by AndroidIntexh1 on 2018/6/4.
 */

public class PartnerMachineFragment extends BaseFragment {
    @BindView(R.id.fragment_recycleView)
    RecyclerView mRecycleView;

    Unbinder unbinder;

    private int page = 1; // 当前页数
    private int position;  // 当前viewPage的位置


    private List<Mystock.myMachineToolsList.List> dataBeansOne = new ArrayList<>();
    private NoActMachineAdapter mbAdapter; //


    private List<Mystock.myMachineToolsList.List> dataBeansTwo = new ArrayList<>(); //
    private ActMachineAdapter mpAdapter; //
    private String searchKey = "";
    private String goods_id;
    private String others_member_id;
    private int pagesize = 10;

    public static PartnerMachineFragment NewInstance(int instanceType, String goods_id, String others_member_id) {
        Bundle bundle = new Bundle();
        bundle.putInt("position", instanceType);
        bundle.putString("goods_id", goods_id);
        bundle.putString("others_member_id", others_member_id);
        PartnerMachineFragment fragment = new PartnerMachineFragment();
        fragment.setArguments(bundle);
        return fragment;
    }


    /**
     * 获取布局文件
     *
     * @return
     */
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_recycleview;
    }


    /**
     * 初始化操作步骤
     */
    @Override
    protected void init() {
        unbinder = ButterKnife.bind(this, rootView);
        position = getArguments().getInt("position");
        goods_id = getArguments().getString("goods_id");
        others_member_id = getArguments().getString("others_member_id");
    }

    /**
     * 初始化界面
     */
    @Override
    protected void initView() {
        initRecycle();
        loadData();
    }

    /**
     * 加载数据
     */
    private void loadData() {
        Mystock.myMachineToolsList.Builder builder = Mystock.myMachineToolsList.newBuilder();
        builder.setGoodsId(goods_id);
        if (ValidateUtils.isValidate(others_member_id)) builder.setOthersMemberId(others_member_id);
        if (position == 0) {
            builder.setMachineType("1");
            NetworkManager.INSTANCE.post(Apis.myMachineToolsList, builder.build().toByteArray(), page, new OnRequestCallBack() {
                @Override
                public void onOk(byte[] response) throws InvalidProtocolBufferException {
                    Mystock.myMachineToolsList list = Mystock.myMachineToolsList.parseFrom(response);
                    List<Mystock.myMachineToolsList.List> datas = list.getListList();
                    mbAdapter.addData(datas);
                    int size = datas.size();
                    if (size < 10) {
                        mbAdapter.loadMoreEnd(true);
                    } else {
                        mbAdapter.loadMoreComplete();
                    }
                    ((PartnerMachineDetailActivity) getActivity()).changeTabTitle(position, list.getTotalGoodsCountNum());
                }

                @Override
                public void onError(int errorCode, String errorMessage) {

                }
            });
        } else if (position == 1) {
            builder.setMachineType("2");
            NetworkManager.INSTANCE.post(Apis.myMachineToolsList, builder.build().toByteArray(), page, new OnRequestCallBack() {
                @Override
                public void onOk(byte[] response) throws InvalidProtocolBufferException {
                    Mystock.myMachineToolsList list = Mystock.myMachineToolsList.parseFrom(response);
                    List<Mystock.myMachineToolsList.List> datas = list.getListList();
                    mpAdapter.addData(datas);
                    int size = datas.size();
                    if (size < 10) {
                        mpAdapter.loadMoreEnd(true);
                    } else {
                        mpAdapter.loadMoreComplete();
                    }
                    ((PartnerMachineDetailActivity) getActivity()).changeTabTitle(position, list.getTotalGoodsCountNum());
                }

                @Override
                public void onError(int errorCode, String errorMessage) {
                }
            });
        }
    }


    /**
     * 实例化线性底部RecyclerView
     * *
     */
    private void initRecycle() {
        mRecycleView.setLayoutManager(new LinearLayoutManager(mContext));
        if (position == 0) {
            mRecycleView.setAdapter(mbAdapter = new NoActMachineAdapter(mContext, dataBeansOne));
            mbAdapter.bindToRecyclerView(mRecycleView);
            mbAdapter.setEmptyView(R.layout.recycle_empty);
            // 每个item的点击事件
            mbAdapter.setOnItemClickListener((adapter, view, position) -> {

            });
            mbAdapter.setOnLoadMoreListener(() -> {
                page = mbAdapter.getData().size() / pagesize + 1;
                loadData();

            }, mRecycleView);
        } else if (position == 1) {
            mRecycleView.setAdapter(mpAdapter = new ActMachineAdapter(mContext, dataBeansTwo));
            mpAdapter.bindToRecyclerView(mRecycleView);
            mpAdapter.setEmptyView(R.layout.recycle_empty);
            // 每个item的点击事件
            mpAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                }
            });
            mpAdapter.setOnLoadMoreListener(() -> {
                page = mpAdapter.getData().size() / pagesize + 1;
                loadData();
            }, mRecycleView);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    public void searchData(String searchKey) {
        this.searchKey = searchKey;
        page = 1 ;
        if (TextUtils.isEmpty(searchKey)) {
            if (position == 0) {
                dataBeansOne.clear();
                mbAdapter.replaceData(dataBeansOne);
            } else {
                dataBeansOne.clear();
                mpAdapter.replaceData(dataBeansTwo);
            }
            loadData();
        } else {
            searchLoadData();
        }

    }

    private void searchLoadData() {
        Mystock.searchSNCodeGoods.Builder builder = Mystock.searchSNCodeGoods.newBuilder();
        builder.setSnCode(searchKey);
        if (position == 0) {
            builder.setMachineType("1");
            NetworkManager.INSTANCE.post(Apis.searchSNCodeGoods, builder.build().toByteArray(), page, new OnRequestCallBack() {
                @Override
                public void onOk(byte[] response) throws InvalidProtocolBufferException {
                    Mystock.searchSNCodeGoods list = Mystock.searchSNCodeGoods.parseFrom(response);
                    List<Mystock.searchSNCodeGoods.List> temp_datas = list.getListList();
                    List<Mystock.myMachineToolsList.List> datas = new ArrayList<>();
                    for (int i = 0; i < temp_datas.size(); i++) {
                        Mystock.myMachineToolsList.List.Builder builder = Mystock.myMachineToolsList.List.newBuilder();
                        builder.setIsActivation(temp_datas.get(i).getIsActivation())
                                .setActicationTime(temp_datas.get(i).getActicationTime())
                                .setSnCode(temp_datas.get(i).getSnCode())
                                .setAssessTime(temp_datas.get(i).getAssessTime())
                                .setGoodsSerial(temp_datas.get(i).getGoodsSerial())
                                .setGoodsId(temp_datas.get(i).getGoodsId())
                                .setGoodsName(temp_datas.get(i).getGoodsName())
                                .setGoodsPrice(temp_datas.get(i).getGoodsPrice())
                                .setGoodsImage(temp_datas.get(i).getGoodsImage());
                        datas.add(builder.build());
                    }
                    mbAdapter.replaceData(datas);
                    int size = datas.size();
                    if (size < 10) {
                        mbAdapter.loadMoreEnd(true);
                    } else {
                        mbAdapter.loadMoreComplete();
                    }
                    ((PartnerMachineDetailActivity) getActivity()).changeTabTitle(position, "1");
                }

                @Override
                public void onError(int errorCode, String errorMessage) {

                }
            });
        } else if (position == 1) {
            builder.setMachineType("2");
            NetworkManager.INSTANCE.post(Apis.searchSNCodeGoods, builder.build().toByteArray(), page, new OnRequestCallBack() {
                @Override
                public void onOk(byte[] response) throws InvalidProtocolBufferException {
                    Mystock.searchSNCodeGoods list = Mystock.searchSNCodeGoods.parseFrom(response);
                    List<Mystock.searchSNCodeGoods.List> temp_datas = list.getListList();
                    List<Mystock.myMachineToolsList.List> datas = new ArrayList<>();
                    for (int i = 0; i < temp_datas.size(); i++) {
                        Mystock.myMachineToolsList.List.Builder builder = Mystock.myMachineToolsList.List.newBuilder();
                        builder.setIsActivation(temp_datas.get(i).getIsActivation())
                                .setActicationTime(temp_datas.get(i).getActicationTime())
                                .setSnCode(temp_datas.get(i).getSnCode())
                                .setAssessTime(temp_datas.get(i).getAssessTime())
                                .setGoodsSerial(temp_datas.get(i).getGoodsSerial())
                                .setGoodsId(temp_datas.get(i).getGoodsId())
                                .setGoodsName(temp_datas.get(i).getGoodsName())
                                .setGoodsPrice(temp_datas.get(i).getGoodsPrice())
                                .setGoodsImage(temp_datas.get(i).getGoodsImage());
                        datas.add(builder.build());
                    }
                    mpAdapter.replaceData(datas);
                    int size = datas.size();
                    if (size < 10) {
                        mpAdapter.loadMoreEnd(true);
                    } else {
                        mpAdapter.loadMoreComplete();
                    }
                    ((PartnerMachineDetailActivity) getActivity()).changeTabTitle(position, "1");
                }

                @Override
                public void onError(int errorCode, String errorMessage) {
                }
            });
        }


    }
}
